/*音乐播放效果的一个插件,需要传canvas和播放器的id进来
 * options参数可以不传 现在调用会出问题,也许以后用的上
 * */
(function($){
	window.AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext;

	function Media(mycanvas,mymusic,options) {
		this.canvas = mycanvas;
		this.mymusic = mymusic;
		this.options = $.extend({},Media.Default,options);
		this._init(this.canvas,this.mymusic);
	}
	
	//参数的默认值
	Media.Default = {
		"cwidth":500,            //canvas的宽度
		"cheight":30,            //canvas的高度
		"capStyle":"#fff",      //填充颜色
		"capYPositionArray":[], //位置数组
		"meterWidth":10,        //占宽
		"capHeight":2,          //
		"meterNum":500/(10+2),   //设定的数量
	}

	Media.prototype = {
		_init:function (canvas,mymusic) {
			this.canvas =document.getElementById(canvas),
			audio = document.getElementById(mymusic);
			var audioCtx = new AudioContext(),
			analyser = audioCtx.createAnalyser(),
			audioSrc = audioCtx.createMediaElementSource(audio); //创建音频节点
			audioSrc.connect(analyser);
			analyser.connect(audioCtx.destination);
			var frequencyData = new Uint8Array(analyser.frequencyBinCount);
			ctx = this.canvas.getContext('2d');
			/*创建线性渐变,增加颜色的过度*/
			var  gradient = ctx.createLinearGradient(0, 0, 0, 110);
			gradient.addColorStop(1, '#0f0');
			gradient.addColorStop(0.5, '#ff0');
			gradient.addColorStop(0, '#f00');
			
			capYPositionArray = [];
			var  cwidth = this.options.cwidth,
				cheight = this.options.cheight,
				meterNum = this.options.meterNum,
				meterWidth = this.options.meterWidth,
				capHeight = this.options.capHeight,
				capStyle = this.options.capStyle;
			_renderFrame();

			function  _renderFrame() {
				var array = new Uint8Array(analyser.frequencyBinCount);
				analyser.getByteFrequencyData(array);  //频率数据存到数组中
				var step = Math.round(array.length / meterNum);
				ctx.clearRect(0, 0, cwidth, cheight);  //清空canvas区域,重新绘图
				for (var i = 0; i < meterNum; i++) {
					var value = array[i * step ];
					if (capYPositionArray.length < Math.round(meterNum)) {
						capYPositionArray.push(value);
					};
					ctx.fillStyle = capStyle;  //填充的样式
					if (value < capYPositionArray[i]) {
						ctx.fillRect(i * 12, cheight - (--capYPositionArray[i])/3, meterWidth, capHeight);
					} else {
						ctx.fillRect(i * 12, cheight - value/3, meterWidth, capHeight);
						capYPositionArray[i] = value;
					};
					ctx.fillStyle = gradient;
					ctx.fillRect(i * 12  , cheight - value/3 + capHeight, meterWidth, cheight); //the meter
				}
				requestAnimationFrame(_renderFrame)
			}      
		}
	}

	$.extend({
		Media:function(mycanvas,mymusic,options){
			new Media(mycanvas,mymusic,options);
		}
	})
})(jQuery)